/*
 * $id:ext/jquery/plugins/jquery.oscProductImage.js 
 *
 * oscProductImage version 2.0
 *
 * Copyright 2011, Zaenal Muttaqin
 * http://blog.lokamaya.net - http://lokamaya.com
 *
 * Licensed under the MIT license:
 * http://creativecommons.org/licenses/MIT/
 *
**/

/* oscProductImage CLASS */
var oscProductImage = {
    options: {
        ajaxURL: 'admin/productimage.php',
        imageURL: {path:'images/', relative:'', medium:'images/thumbs/def/adminpreview/', small:'images/thumbs/def/adminthumb/', transparent:'images/pixel_trans.gif'},
        privileges: {directory:1,deletes:1},
        language_id:'1',
        products_images: '',
        allowedExtensions: 'gif|jpg|jpeg|png',
        buttons: {add:'Add', back:'Back', cancel:'Cancel', close:'Close', confirm:'Confirm', create:'New Directory', deletes:'Delete', oke:'Ok', preview:'Preview', remove:'Remove', save:'Save', submit:'Submit', upload:'Upload', xBrowse:'Browse Server', xHelp:'Help', xUpload:'Upload Image'},
        labels: {add:'Add to Product', create:'Create New Directory', dirBrowse:'Browse Directory', dirNew:'New Directory', dirTarget:'Target Directory', deletes:'Delete from Server', preview:'Preview Image', remove:'Remove from Product', tips:'* Drag the image to short', page:'Page', of:'of', from:'From', files:'files', pleaseSelect:'Select:'},
        messages: {
            unknown: 'Unknown error', //0
            
            confirm_remove: 'Remove this image from current product?', //1 - confirm
            confirm_delete: 'Delete this image from server?', //2 - confirm
            
            success_upload: 'Success: Image has been uploaded successfully', //3 - success
            success_create: 'Success: New directory has been created', //4 - success
            success_delete: 'Success: Image has been deleted from server', //5 - success

            error_not_exist: 'Error: Directory does not exist', //6 - error global
            error_not_writable: 'Error: File/directory is not writeable', //7 - error global
            error_not_readable: 'Error: directory does not exist/readable', //8 - error global

            warning_empty_folder: 'There is no image in this directory', //9 - warning browse
            error_delete_global: 'Can not delete image: file is not writeable or not found', //10 - error browse: delete image
            error_delete_empty: 'Can not delete image: file is not writeable or not found', //10 - error browse: delete image
            error_delete_in_use: 'Can not delete image: image still in use by other products', //10 - error browse: delete image
            error_delete_privilege: 'Can not delete image: you have no privilege to delete image', //11 - error browse: delete image

            error_select_directory: 'Please select target directory', //12 - error upload/create directory
            error_file_empty: 'Please select file to upload', //13 - error upload: file empty
            error_file_extension: 'Extension not allowed', //14 - error upload: extension
            
            error_create_privilege: 'You have no privilege to create new directory', //15 - error create directory
            error_create_exist: 'Directory already exists', //16 - error create directory
            error_create_empty: 'Directory name is empty or less than 4 characters', //17 - error create directory
            error_create_alphanumeric: 'Only alphanumeric, dash and underscore are allowed for directory name', //18 - error create directory
            error_create_lowercase: 'Directory name must be in lowercase', //19 - error create directory
            error_create_character: 'Directory name should not be started with dash or underscore', //20 - error create directory
        },
        sessionLife: 1440000,
        cleanup: false
    },
    
    initialize: function(filefield, options) {
        var that = this;
        options = options || {};
        $.extend(this.options, options);
        
        this.timerReset(true);
        this.dialogReset = true;
        
        //find products_image file field
        var products_image_field = $('input[name="'+filefield+'"]');
        if (!products_image_field.length) {
            alert("Field "+filefield+" not found! OsC Product Images Module can not be initialized");
            return;
        }
        this.directoryLoaded = null;
        this.processTemplate(products_image_field);
        //this.selectOptionCurrentDirectory = null;
        
        window.URL = window.URL || window.webkitURL || URL || webkitURL || null;
        if (window.URL && (typeof window.URL.createObjectURL).toLowerCase() != 'undefined') {
            $('#uploadPreview').addClass('available');
        } else {
            window.URL = false;
        }
        
        if (this.options.cleanup === true) this.doCleanUp();
    },
    
    //to prevent losing session
    timerSess: null,
    timerAccess: null,
    timerTimeout: 0,
    timerReset: function(setup) {
        var date = new Date();
        var msec = date.getTime();
        this.timerSess = this.options.sessionLife ? Math.round(this.options.sessionLife/2) : 0;
        this.timerAccess = this.timerAccess || msec;
        
        if (setup) {
            this.timerSetup();
        } else if (msec - this.timerSess > this.timerAccess) {
            this.timerCall();
        }
    },
    timerSetup: function(call){
        if (!this.options.sessionLife || !this.timerSess) return;
        
        var that = this;
        this.timerTimeout = setTimeout(function() {that.timerSetup(true);}, that.timerSess);
        this.timerSess = this.timerSess + Math.round(this.timerSess/10);
        if (call) that.timerCall();
    },
    timerCall: function() {
        var that = this, date = new Date();
        this.timerAccess = date.getTime();
        $.getJSON(that.options.ajaxURL+'?action=timer', function(data) {
                if (!data || !data.time) {
                    that.options.sessionLife = 0;
                    if (that.timerTimeout) clearTimeout(that.timerTimeout);
                }
        });
    },
    
    showLoader: function(dialogs) {
        return this.showHideMessage({loader:true, dialog:dialogs});
    },
    showHideMessageTM:null,
    showHideMessageTMID:null,
    showHideMessage: function(opt, dialogs) {
        if (opt=="hide" && dialog) {
            $(dialogs).find('div.loader').html("").hide();
            if (this.showHideMessageTM && this.showHideMessageTMID.attr('id') == $(dialogs).attr('id')) {
                    clearTimeout(this.showHideMessageTM);
                    this.showHideMessageTM = null;
            }
            return;
        }
       
        var that = this;
        var dialog  = opt.dialog || dialogs || null;
        var loader  = opt.loader || null;
        var timeout = opt.timeout || 5000;
        
        
        var messageText  = '';
        var errorText  = opt.text || null;
        var errorCode  = opt.error || opt.success || opt.warning || null;
        var errorClass = opt.error ? 'error' : (opt.success ? 'success' : 'warning');
        var add        = opt.add || false;
        add = opt.first ? false : add;
        
        if (errorCode && !this.options.messages[errorCode]) errorCode = 'unknown';
        //errorNumber = errorNumber ? parseInt(errorNumber) : null;
        
        if (loader || (errorText === null && errorCode===null)) {
            dialog = dialog || $('div.opiDialog:visible');
            return $(dialog).find('div.loader').fadeOut(1, function() {
                    $(this).html('<div class=""></div>').fadeIn("fast");
            });
        }

        messageText = errorText;
        if (errorCode == 'unknown' && !messageText) {
            messageText = this.options.messages['unknown'];
        } else if (errorCode && this.options.messages[errorCode]) {
            messageText = this.options.messages[errorCode];
            if (errorText) messageText += ' :: ' + errorText;
        }
        
        if (dialog) {
            if (!add) {
                if (this.showHideMessageTM && this.showHideMessageTMID.attr('id') == $(dialog).attr('id')) {
                    clearTimeout(this.showHideMessageTM);
                    this.showHideMessageTM = null;
                }
                
                this.showHideMessageTMID = $(dialog).find('div.loader').html('').hide().delay(100).fadeIn();
                this.showHideMessageTM = setTimeout(function() {
                        $(dialog).find('div.loader').fadeOut();
                }, timeout);
            }
            return $(dialog).find('div.loader').append('<ul class="'+errorClass+'"><li>'+messageText+'</li></ul>');
            //$('<ul class="'+errorClass+'"><li>'+messageText+'</li></ul>').appendTo($(dialog).find('div.loader'));
            //.fadeOut(1, function(){$(this).append()}).fadeIn(1).delay(10).effect("highlight").delay(timeout).fadeOut("slow", function(){that.showHideMessage(); callback();});
        } else {
            $('#opiAlertDialog').find('div.content').html(messageText);
            return $('#opiAlertDialog').dialog("open");
        }
    },
    
    doCleanUp: function() {
        var data = {}, that=this;
        $.getJSON(this.options.ajaxURL+'?action=cleanUp', function(data) {
                if (data) {
                    output = data.output || [];
                    if (data.error) {
                        that.showHideMessage({error:data.error, text:data.output});
                    }
                }
        });
    },
    
    directoryLoaded: null,
    doGetDirectories: function(callback) {
        this.timerReset();
        //var callback = callback || function(){};
        
        var data = {}, that=this;
        $.getJSON(this.options.ajaxURL+'?action=getDirectories', function(data) {
                var output = [];
                if (data) {
                    output = data.output || [];
                    if (data.error) {
                        that.showHideMessage({error:data.error, text:data.output});
                    } else {
                        that.directoryLoaded = output;
                        if (jQuery.isFunction( callback )) callback();
                    }
                }
        });
    },
    
    doTestGetDirectories: function(elem, selectedIndex, callback) {
        var that=this;
        var dialog = elem.closest('div.opiDialog');
        var selectedIndex = parseInt(selectedIndex)==(selectedIndex) ? selectedIndex : 0;
        elem.attr('defaultSelected', selectedIndex);
        
        dialog.addClass('opiDialogLoading');
        
        var processDirectory = function() {
            if (!that.directoryLoaded || that.directoryLoaded.length < 1) {
                that.showHideMessage({error:'warning_empty_folder', dialog:dialog});
            }
            populateElement();
            dialog.removeClass('opiDialogLoading');
            if (callback) callback();
        };
        
        var populateElement = function() {
            var sel = elem.parent(), uls = sel.find('ul'), j=0, selectedClass = (j==selectedIndex) ? 'selected ui-priority-primary' : 'ui-priority-secondary';
            //clean-up elements
            elem.find('option').remove();
            uls.find('li').remove();
            //add default value
            $('<option value="">'+that.options.labels.pleaseSelect+'</option>').appendTo(elem);
            $('<li class="opilist ui-state-default '+selectedClass+'" title="" value="'+j+'">'+that.options.labels.pleaseSelect+'</li>').appendTo(uls);
            j++;
            //populate
            if (!that.directoryLoaded || that.directoryLoaded.length < 1) {
                $('<option value="">/</option>').appendTo(elem);
                $('<li class="opilist ui-state-default '+selectedClass+'" title="" value="'+j+'">/</li>').appendTo(uls);
                j++;
            } else {
                $.each(that.directoryLoaded, function(i, val) {
                    selectedClass = (j==selectedIndex) ? 'selected ui-priority-primary' : 'ui-priority-secondary';
                    $('<option value="'+val+'">/'+val+'</option>').appendTo(elem);
                    $('<li class="opilist ui-state-default '+selectedClass+'" title="'+val+'" value="'+j+'">/'+val+'</li>').appendTo(uls);
                    j++;
                });
            }
            
            elem.attr('selectedIndex',0);
            uls.find('li:first').hide();
            if (selectedIndex > 0) elem.triggerHandler('focusin');
        };
        
        if (!that.directoryLoaded) {
            that.doGetDirectories(processDirectory);
        } else {
            if (that.directoryLoaded.length != (elem.find('option').length - 1)) {
                processDirectory();
            }
            dialog.removeClass('opiDialogLoading');
        }
    },
    
    doUpload: function() {
        var that = this;
        var output = window.frames['opiUploadFrame'].output ? window.frames['opiUploadFrame'].output : '{}';
        var data = jQuery.parseJSON(output) || {};
        var dialogs = $('#opiUploadDialog');
        if (data && data.output) {
            if (data.error) {
                this.showHideMessage({ error:data.error, text:data.output, dialog:dialogs });
            } else {
                this.imageAddProcess(data.output, true);
                var last = $('#opiImageList').find('li:last').find('div.img').addClass('animated');
                $('#uploadInProcess').remove();
                $('#uploadPreviewImage').effect("transfer", { to: $(last), className:'ui-effects-transfer ui-effects-transfer-border transferedUI'}, "slow", function() {
                        $(this).find('div').css({opacity:0.5});
                        $(last).removeClass('animated');
                        that.showHideMessage({ success:'success_upload', dialog:dialogs});
                });
                $('.transferedUI').ready(function() {
                        $('.transferedUI').css({opacity:1}).animate({opacity:0}, "slow");
                        that.checkImagePreview();
                });
                
                dialogs.find('form').find('input[type="file"]').val('').triggerHandler('change');
                
                var sel1 = dialogs.find('form').find('select').get(0);
                var sel2 = $('#opiBrowseDialog').find('form').find('select').get(0);
                if (sel1 && sel2 && $(sel1).attr("selectedIndex") == $(sel2).attr("selectedIndex")) {
                    $($('#opiBrowseDialog').find('form').get(0)).triggerHandler('submit');
                }
            }
            $('#uploadBtnSubmit').button("option", "disabled", false);
            //redirect iframe to blank page... 
            //so it would not send duplicate upload when user refresh (F5) the browser
            try {window.frames['opiUploadFrame'].location.href="about:blank";} catch(e){try{$('#opiUploadFrame').attr('src', "about:blank");} catch(e){}}
        }
    },
    
    doTestUpload: function(form) {
        this.timerReset();
        var form = $(form), that=this;
        form.find(".ui-state-error").removeClass("ui-state-error");
        $('#uploadBtnSubmit').button("option", "disabled", true);

        var inputdir  = form.find('select[name="opi_folder"]');
        var inputfile = form.find('input[type="file"]');
        var regexs    = new RegExp("(\.|\/)("+that.options.allowedExtensions+")$", "i");
        
        var error = false;
        if (inputdir.attr('selectedIndex') == 0) {
            that.showHideMessage({error:'error_select_directory', first:true, dialog:form.closest('div.opiDialog')});
            inputdir.closest('div.selector').find('div.ui-state-default, button.ui-state-default').addClass("ui-state-error");
            error = true;
        }
        if ((inputfile.val()).length < 1) {
            that.showHideMessage({error:'error_file_empty', add:(error===true), dialog:form.closest('div.opiDialog')});
            inputfile.closest('div.selector').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        } else if (!regexs.test(inputfile.val())) {
            that.showHideMessage({error:'error_file_extension', add:(error===true), dialog:form.closest('div.opiDialog')});
            inputfile.closest('div.selector').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        }
            
        if (error) {
            $('#uploadBtnSubmit').button("option", "disabled", false);
            return false;
        }
        var zIndexs = parseInt($('div.ui-widget-overlay:last').css('z-index')) + 100;
        var zHeight = parseInt($(window).height());
        var zWidth  = parseInt($(window).width());
        //var zIndexs = parseInt(layer.css('z-index')) + 100;
        //alert(zIndexs);
        //return false;
        $('<div id="uploadInProcess" />').css({width:zWidth, height:zHeight, zIndex:zIndexs}).html('<span></span><div><br />...upload in process</div>').find('span').css({opacity:0.8}).parent().appendTo($(document.body));
        //$( '<div />' ).appendTo($(document.body)).attr('id', 'uploadInProcess').append('<div>Please wait... upload in process</div>');
        //that.showLoader(form.closest('div.opiDialog'));
        return true;
    },
    
    doCreateDirectory: function(forms) {
        var that = this;
        var dialogs = $('#opiDirectoryDialog');
        this.timerReset();
        $.post(this.options.ajaxURL+'?action=createDirectory', $(forms).serialize(), function(data) {
                if (data) {
                    if (data.error) {
                        that.showHideMessage({error:data.error, text:data.output, dialog:dialogs});
                        $('#createBtnSubmit').button("option", "disabled", false);
                    } else {
                        that.directoryLoaded = null;
                        $('#opi_directory').val('');
                        that.doTestGetDirectories(dialogs.find('form').find('select[name="opi_folder"]'), 1, function() {
                                that.doTestGetDirectories($('#opiUploadDialog').find('select[name="opi_folder"]'), 1);
                                that.showHideMessage({success: 'success_create', dialog: dialogs});
                                $('#createBtnSubmit').button("option", "disabled", false);
                        });
                    }
                }
        }, "json");
        
        return true;
    },
    
    doTestCreateDirectory: function(form) {
        this.timerReset();
        var form = $(form), that=this;
        form.find(".ui-state-error").removeClass("ui-state-error");
        $('#createBtnSubmit').button("option", "disabled", true);

        var inputdir  = form.find('select[name="opi_folder"]');
        var inputname = form.find('input[name="opi_directory"]');
        var regexs    = new RegExp("[^a-z0-9\-_]", "i");
        var regexs2   = new RegExp("^[a-z0-9]", "i");
        
        var error = false;
        if (inputdir.attr('selectedIndex') == 0) {
            that.showHideMessage({error:'error_select_directory', first:true, dialog:form.closest('div.opiDialog')});
            inputdir.closest('dd').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        }
        
        if ((inputname.val()).length < 4) {
            that.showHideMessage({error:'error_create_empty', add:(error===true), dialog:form.closest('div.opiDialog')});
            inputname.closest('dd').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        } else if (regexs.test(inputname.val())) {
            that.showHideMessage({error:'error_create_alphanumeric', add:(error===true), dialog:form.closest('div.opiDialog')});
            inputname.closest('dd').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        } else if (!regexs2.test(inputname.val())) {
            that.showHideMessage({error:'error_create_character', add:(error===true), dialog:form.closest('div.opiDialog')});
            inputname.closest('dd').find('.ui-state-default, .ui-state-highlight, .ui-state-hover, .ui-state-active').addClass("ui-state-error");
            error = true;
        }
            
        if (error) {
            $('#createBtnSubmit').button("option", "disabled", false);
            return false;
        }
        that.showLoader(form.closest('div.opiDialog'));
        return true;
    },
    
    doDelete: function(elem) {
        var that = this;
        this.timerReset();
        this.showHideMessage("hide", $('#opiBrowseDialog'));
        var img = $(elem).addClass('deleted').attr('title');
        $.post(this.options.ajaxURL+'?action=delete', { opi_delete:img }, function(data) {
                var output = '';
                if (data) {
                    output = data.output || 'not found!';
                    if (data.error) {
                        $(elem).removeClass('deleted');
                        that.showHideMessage({error:data.error, text:data.output});
                    } else {
                        that.listBrowseImageDelete(elem);
                    }
                }
        }, "json");
    },
    
    doBrowseFiles: function(forms) {
        var that = this;
        this.timerReset();
        this.showHideMessage("hide", $('#opiBrowseDialog'));
        $('#opiBrowseDialog').addClass('opiBrowseLoading');
        $.post(this.options.ajaxURL+'?action=browseFiles', $(forms).serialize(), function(data) {
                var output = [];
                if (data) {
                    output = data.output || [];
                    if (data.error) {
                        that.showHideMessage({error:data.error, text:data.output});
                    } else {
                        that.listBrowseImagePopulate(output);
                    }
                }
                $('#opiBrowseDialog').removeClass('opiBrowseLoading');
        }, "json");
        
        return false;
    },
    
    listBrowseImagePage: 1,
    listBrowseImagePageItems: 8,
    listBrowseImageTotal: 0,
    listBrowseImagePopulate: function(output) {
        var that = this;
        $('#opiImageBrowse').find('li').remove();
        this.listBrowseImagePage = 0;
        this.listBrowseImageTotal = output.length;
        
        if (this.listBrowseImageTotal > 0) {
            $.each(output, function(i,img){
                    that.imageAddProcess(img);
            });
        } else {
            this.showHideMessage({error:'warning_empty_folder', dialog:$('#opiBrowseDialog')});
        }
        this.listBrowseImagePrevNext(0);
    },
    
    listBrowseImageDelete: function(elem) {
        var that = this;
        $(elem).addClass('deleted');
        $(elem).css({opacity:1}).animate({opacity:0}, "slow", "swing", function() {
                $(this).animate({width:0, height:1}, "fast", "swing", function(){
                        that.listBrowseImageTotal--;                        
                        that.listBrowseImagePrevNext(0, $(this));
                        $(this).remove();
                });
        });
    },
    
    listBrowseImagePrevNext: function(prevnext, noreload) {
        var that=this, li = $('#opiImageBrowse').find('li'), noreload = (noreload || false);
        this.timerReset();
        //this.showHideMessage("hide", $('#opiBrowseDialog'));
        
        $('#btnBrowsePrev').button("option", "disabled", true);
        $('#btnBrowseNext').button("option", "disabled", true);
        if (!noreload) li.hide();
        
        prevnext = prevnext || 0;
        
        totItem = this.listBrowseImageTotal > 0 ? this.listBrowseImageTotal : 1;
        maxItem = this.listBrowseImagePageItems;
        maxPage = Math.ceil(totItem / maxItem); 
        minPage = 1;
        newPage = this.listBrowseImagePage + prevnext;
        //if (this.listBrowseImagePage == newPage) return;
        
        oldMaxPage = this.listBrowseImagePage;
        if (newPage < minPage) newPage = 1;
        else if (this.listBrowseImagePage > maxPage) this.listBrowseImagePage = maxPage;
        this.listBrowseImagePage = newPage;
        
        var showingItem = 0;
        var addedImages = [];
        $('#opiImageList').find('input[type="hidden"]').each(function() {
                addedImages.push(this.value);
        });
        $('#opiBrowseDialog').removeClass('opiBrowseLoading');
        
        var fade = 150;
        var next = null;
        if (!noreload) {
            var iMin = (newPage*maxItem) -maxItem;
            var iMax = (iMin + maxItem) > li.length ? li.length : iMin + maxItem;
            next = li.slice(iMin, iMax);
        } else {
            if (oldMaxPage > maxPage) return this.listBrowseImagePrevNext(-1);
            try {
                next = $(noreload).next();
                while(next.length > 0 && next.is(":visible")) next = $(next).next();
            } catch(e) {
                next = null;
                return this.listBrowseImagePrevNext(-1);
            }
        }
        
        $.each(next, function(i) {
                var imgFile = $(this).attr('title');
                var listing = $(this);
                
                var callbackPreload = function(imgSrc) {
                    listing.find('div.img').html('').removeClass('loading');
                    $('<img />').hide().appendTo(listing.find('div.img')).attr({title: imgFile, src:imgSrc}).fadeIn();
                };
                
                if (!listing.find('img').length) {
                    that.preloadImage(that.options.imageURL.small + imgFile, callbackPreload);
                }
                if (jQuery.inArray(imgFile, addedImages) >= 0) {
                    $(this).css({opacity:0.5}).find('button').button("option", "disabled", true);
                } else {
                    $(this).css({opacity:1}).find('button').button("option", "disabled", false);
                    $(this).find('button.btnDel').button("option", "disabled", !that.options.privileges.deletes);
                }
                $(this).hide().delay(fade).fadeIn();
                fade = fade + 250;
        });
        setTimeout(function() {
                $('#btnBrowsePrev').button("option", "disabled", (that.listBrowseImagePage <= minPage));
                $('#btnBrowseNext').button("option", "disabled", (that.listBrowseImagePage >= maxPage));
        }, fade+350);

        var label = [newPage, maxPage, this.listBrowseImageTotal];
        $('#btnBrowseNext').closest('div.ui-dialog-buttonpane').find('label.page_index').each(function(i) {
                $(this).html(label[i]);
        });
    },
    
    imageAddProcess: function(imgFile, main) {
        var that=this;
        var uls = main ? $('#opiImageList') : $('#opiImageBrowse');
        var listing = $('<li class="opi ui-state-default" title="'+imgFile+'"></li>').appendTo(uls);
        listing.append('<div class="rel"><div class="img loading"></div><div class="buttons"></div></div>');
        
        var callbackPreload = function(imgSrc) {
            listing.find('div.img').html('').removeClass('loading');
            $('<img />').hide().appendTo(listing.find('div.img')).attr({title: imgFile, src:imgSrc}).fadeIn();
        };
        
        if (main) {
            listing.find('div.buttons').append('<input type="hidden" name="products_images[]" value="'+imgFile+'" />');
            $('<button class="btnRemove" title="'+this.options.labels.remove+'" type="button">'+this.options.buttons.remove+'</button>').appendTo(listing.find('div.buttons')).button({label: '', icons:{secondary:"ui-icon-close"}}).addClass("ui-priority-secondary  ui-icon-centered");
            $('<button class="btnPreview" title="'+this.options.labels.preview+'" type="button">'+this.options.buttons.deletes+'</button>').appendTo(listing.find('div.buttons')).button({label: '', icons:{secondary:"ui-icon-circle-zoomin"}}).addClass("ui-priority-primary  ui-icon-centered");
            that.preloadImage(that.options.imageURL.small + imgFile, callbackPreload);
        } else {
            $('<button class="btnDel" title="'+this.options.labels.deletes+'" type="button">'+this.options.buttons.deletes+'</button>').appendTo(listing.find('div.buttons')).button({label: '', icons:{secondary:"ui-icon-trash"}}).addClass("ui-priority-secondary  ui-icon-centered");
            $('<button class="btnAdd" title="'+this.options.labels.add+'" type="button">'+this.options.buttons.add+'</button>').appendTo(listing.find('div.buttons')).button({label: '', icons:{secondary:"ui-icon-circle-plus"}}).addClass("ui-priority-primary ui-icon-centered");
        }
    },
    
    clickButtonDelete: function(elem) {
        if (this.options.privileges.deletes) {
            if (confirm(this.options.messages['confirm_delete'])) {
                return this.doDelete(elem);
            }
        } else {
            that.showHideMessage({error:'error_delete_privilege'});
        }
    },
    
    clickButtonAdd: function(elem) {
        var that=this, imgimg = $(elem).find('img');
        
        $(elem).find('button').button("option", "disabled", true);
        that.imageAddProcess(imgimg.attr('title'), true);
        var last = $('#opiImageList').find('li:last').find('div.img').addClass('animated');
        $(elem).css({opacity:1}).animate({opacity:0.5}, "slow").find('div.img').effect("transfer", { to: $(last), className:'ui-effects-transfer transferedUI'}, "slow", function() {
                $(last).removeClass('animated');
        });
        $('.transferedUI').ready(function() {
                $('.transferedUI').html('<div><img src="'+imgimg.attr('src')+'" /></div>').find('div').css({opacity:1}).animate({opacity:0}, "slow");
                that.checkImagePreview();
        });
        
        var callbackPreload = function(img) {
            last.siblings().removeClass('previewed');
            last.addClass('previewed');
            $("#opiImageDefault").find('div').find('img').css({opacity:0}).attr({src:img.src, title:imgimg.attr('title')}).animate({opacity:1});
        };
        
        this.preloadErrorImage(that.options.imageURL.medium+imgimg.attr('title'));
    },
    
    clickButtonRemove: function(elem) {
        if (confirm(this.options.messages['confirm_remove'])) {
            //$(this).closest('li.opi').fadeOut("slow", function(){$(this).remove()});
            var other = null;
            if ($(elem).hasClass('previewed')) {
                other = $(elem).prev();
                if (!other || other.length < 1) other = $(elem).next();
                if (other && other.length > 0) {
                    this.clickButtonPreview(other);
                }
            } 
            if (!$(elem).siblings().length) {
                $("#opiImageDefault").removeClass('loading').html('<img src="'+this.options.imageURL.transparent+'" />');
            }
            
            $(elem).css({opacity:1}).animate({opacity:0}, "slow", "swing", function() {
                    $(this).animate({width:0, height:1}, "fast", "swing", function(){$(this).remove()});
            });
        }
    },
    
    clickButtonPreview: function(elem) {
        if (elem.hasClass('previewed')) {
            $("#opiImageDefault").find('img').fadeOut(1).fadeIn("fast");
            return;
        }
        var that = this;
        $(elem).siblings().removeClass('previewed');
        $(elem).addClass('previewed');
        var newImg = $(elem).find('input').val();
        
        var callbackPreload = function(imgSrc) {
            $("#opiImageDefault").addClass('loading').find('img').css('position','absolute').fadeOut("normal", function() {$(this).remove();});
            $('<img />').hide().appendTo($("#opiImageDefault")).attr({title: newImg, src:imgSrc}).fadeIn("slow", function(){$("#opiImageDefault").removeClass('loading')});
        };
        
        $("#opiImageDefault").addClass('loading').find('img').css('position','absolute').fadeOut("normal", function() {$(this).remove();});
        that.preloadImage(that.options.imageURL.medium + newImg, callbackPreload);
    },
    
    checkImagePreview: function() {
        if ($('#opiImageList').find('li').length == 1) {
            this.clickButtonPreview($('#opiImageList').find('li:first'));
        }
    },
    
    clickButtonSorted: function(elem) {
        $("#opiImageDefault").find('img').fadeIn(10);
    },
    
    formDialogUI: function() {
        var that = this;
        
        var formLabelShowHide = function(elem) {
            var parent = elem.closest('div.selector');
            var oVal   = (elem.get(0).nodeName).toLowerCase() == 'select' ? elem.text() : elem.val();  
            
            if (oVal.length > 0) parent.find('label.inside[for="'+elem.attr('id')+'"]').hide();
            else parent.find('label.inside[for="'+elem.attr('id')+'"]').show();
            
            parent.closest('dd').find(".ui-state-error").removeClass("ui-state-error");
        };
        
        var formInput = function(elem) {
            var parent = elem.addClass("opiElement ui-helper-input").wrap('<div class="selector inputWrapper ui-state-default ui-corner-all ui-priority-secondary" />').parent().attr('id', elem.attr('id')+"_selector");
            var title  = elem.attr('title') || null;
            if (title) parent.prepend('<label class="inside inputWrapper" for="'+elem.attr('id')+'">'+title+'</label>');
            
            parent.focusin(function() {
                    parent.find('label.inside[for="'+elem.attr('id')+'"]').hide();
                    parent.closest('dd').find(".ui-state-error").removeClass("ui-state-error");
            });
            parent.focusout(function() {
                    formLabelShowHide(elem);
            }); 
        };
        
        var scaleImage = function (img, options) {
            options = options || {};
            var scale=1, canvas = null; //document.createElement('canvas');
            scale = Math.min(
                (options.maxWidth || img.width) / img.width,
                (options.maxHeight || img.height) / img.height
                );
            
            if (scale >= 1) {
                scale = Math.max(
                    (options.minWidth || img.width) / img.width,
                    (options.minHeight || img.height) / img.height
                    );
            }
            img.width = parseInt(img.width * scale, 10);
            img.height = parseInt(img.height * scale, 10);
            if (!canvas || !options.canvas || !canvas.getContext) {
                return img;
            }
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
            return canvas;
        };
        
        var formFile = function(elem) {
            var parent = elem.addClass("opiElement ui-helper-opacity").wrap('<div class="selector" />').parent().attr('id', elem.attr('id')+"_selector");
            var title  = elem.attr('title') || null;
            
            if (title) parent.prepend('<label class="inside" for="'+elem.attr('id')+'">'+title+'</label>');
                
            $('<input type="text" value="" readonly="readonly" />').appendTo(parent).bind('click', function(e) {
                    elem.triggerHandler('focusin');
            }).bind('focus', function(e) {
                    $(this).blur();
            }).wrap('<div class="inputWrapper ui-state-default ui-corner-all ui-priority-secondary" />');
            
            $('<button type="button" title="'+title+'" class="file">&nbsp;</button>').appendTo(parent).bind('click', function(e) {
                    elem.triggerHandler('focusin');
            }).button({icons:{primary:"ui-icon-folder-open"}}).removeClass('ui-corner-all').addClass('ui-corner-right ui-priority-primary');
            
            
            elem.bind('change', function(e){
                    var form = this.form;
                    //window.URL = (typeof window.createObjectURL !== 'undefined' && window) || (typeof URL !== 'undefined' && URL) || (typeof webkitURL !== 'undefined' && webkitURL) || null;
                    //window.URL = window.URL || window.webkitURL || null;
                    
                    if (window.URL && this.files && this.files.length) {
                        $('#uploadPreviewImage').html('').css({opacity:1});
                        var oFile = this.files[0];
                        oFile.name = oFile.name || oFile.fileName || null;
                        oFile.size = oFile.size || oFile.fileSize || null

                        var url = window.URL.createObjectURL(oFile);                        
                        var oImg = $("<img>");
                        oImg.bind('load', function() {
                                $(this).unbind('load');
                                
                                var data = '<span>' + this.width+" x "+this.height+" Pixel";
                                if (oFile.size) data += " - <strong>" + Math.ceil(oFile.size/1024) + " Kb</strong>";
                                data += '</span>';
                                
                                var obj = scaleImage(this, {maxWidth:240, maxHeight:240});
                                $('#uploadPreviewImage').append('<div></div>');
                                $('#uploadPreviewImage').find('div').hide().append($(obj)).fadeIn();
                                //$('<li class="opiUploadPreview"></li>').appendTo($('#uploadPreview')).hide().append($(obj)).append(data).fadeIn();
                                $('#uploadPreviewInfo').html(data);
                                window.URL.revokeObjectURL(url);
                        });
                        oImg.get(0).src = url; //('src', url);
                        
                    }
                    
                    parent.find('input[type="text"]').val((elem.val()).toLowerCase());
                    formLabelShowHide(elem);
            });
            elem.focusin(function() {return this.click()});
            elem.focusout(function() {return true});
            parent.focusin(function() {
                    parent.find('label.inside[for="'+elem.attr('id')+'"]').hide();
                    parent.closest('dd').find(".ui-state-error").removeClass("ui-state-error");
            });
            parent.focusout(function() {
                    formLabelShowHide(elem);
            }); 
        };
        
        var formSelect = function(elem) {
            var parent = elem.addClass("opiElement ui-helper-opacity").wrap('<div class="selector" />').parent().attr('id', elem.attr('id')+"_selector");
            var title  = elem.attr('title') || null;
            var form   = elem.get(0).form;
            elem.attr('defaultSelected', 0);
            
            if (title) parent.prepend('<label class="inside" for="'+elem.attr('id')+'">'+title+'</label>');
            
            $('<input type="text" value="" readonly="readonly" />').appendTo(parent).bind('click', function(e) {
                    if (parent.find('strong.dropdownContainer').is(":hidden")) {
                        parent.find('strong.dropdownContainer').slideToggle("fast", formSelectScroll);
                    }
                    e.stopImmediatePropagation();
                    e.stopPropagation();
            }).wrap('<div class="inputWrapper ui-state-default ui-corner-all ui-priority-secondary" />');
            
            $('<button type="button" title="'+title+'" class="select">&nbsp;</button>').appendTo(parent).bind('click', function(e) {
                    parent.find('strong.dropdownContainer').slideToggle("fast", formSelectScroll);
                    e.stopImmediatePropagation();
                    e.stopPropagation();
            }).button({icons:{primary:"ui-icon-triangle-1-s"}}).removeClass('ui-corner-all').addClass('ui-corner-right ui-priority-primary');
            
            $('<strong class="dropdownContainer ui-state-default ui-corner-bottom ui-priority-secondary" />').appendTo(parent).slideUp(1).hide().html('<span><ul id="'+elem.attr('id')+'_ulSelector" class="dropdownList"></ul></span>');
            
            $('#'+elem.attr('id')+'_ulSelector').delegate('li', 'click', function(e) {
                    formSelectClicked(elem, parseInt($(this).attr('value'))+0, true);
                    //e.stopImmediatePropagation();
                    e.stopPropagation();
            });
            
            elem.bind('focusin', function() {
                    parent.find('strong.dropdownContainer').hide();
                    var newIndex =  parseInt(elem.attr('defaultSelected'))+0 || 0;
                    elem.attr('defaultSelected', newIndex);
                    formSelectClicked(elem, newIndex);
                    parent.find('input[type="text"]').each(function() {
                            this.defaultValue = elem.find('option:selected').text();
                    });
            });
            elem.bind('focusout', function() {
                    parent.find('strong.dropdownContainer').hide();
                    var newIndex =  parseInt(elem.attr('defaultSelected'))+0 || 0;
                    formSelectClicked(elem, newIndex);
            });
            parent.focusin(function() {
                    parent.find('label.inside[for="'+elem.attr('id')+'"]').hide();
                    parent.closest('dd').find(".ui-state-error").removeClass("ui-state-error");
            });
            parent.focusout(function() {
                    $(this).find('strong.dropdownContainer').slideUp("fast");
                    formLabelShowHide(elem);
            });
            //that.selectOptionPopulate(elem);
        };
        
        var formSelectClicked = function(elem, newIndex, fire) {
            //that.selectOptionClick(parent.find('select'), $(this).attr('title'));
            var parent   = elem.parent();
            var oldIndex = parseInt(elem.attr('selectedIndex'))+0;
            
            if (newIndex != oldIndex) {
                parent.find('li').removeClass('selected ui-priority-primary').addClass('ui-priority-secondary');
                parent.find('li[value="'+newIndex+'"]').removeClass('ui-priority-secondary').addClass('selected ui-priority-primary');
                elem.attr('selectedIndex', newIndex);
                
                var oVal = elem.find('option:selected').text();
                parent.find('input[type="text"]').val(oVal);
                if (oVal.length > 0) parent.find('label.inside').hide();
                else parent.find('label.inside').show();
                    
                if (fire) elem.change();
            }
            if (elem.find('option:selected').text() == '') {
                //
            }
            
            parent.find('strong.dropdownContainer').slideUp();
        };
        
        var formSelectScroll = function () {
            if ($(this).is(":hidden")) return;
            
            var offset=0, sel=$(this).find('li.selected'), span=$(this).find('span');
            if (sel.is(":hidden")) {
                span.animate({scrollTop: offset},'1');
            } else {
                var selPos=((sel.length) ? sel.position().top : 0), maxScroll=span.height()-sel.height();
                offset = selPos + span.scrollTop();
                if (selPos <= 0 || selPos > maxScroll) span.animate({scrollTop: offset},'fast');
            }
        };
        
        //that.doGetDirectories();
        var forms = $('div.opiDialog').find('form');
        
        forms.find('input[type="text"]').each(function(i) {
                this.id = this.id || that.generateID(this, i);
                formInput($(this));
        });
        forms.find('input[type="file"]').each(function(i) {
                this.id = this.id || that.generateID(this, i);
                formFile($(this));
        });
        forms.find('select').each(function(i) {
                this.id = this.id || that.generateID(this, i);
                formSelect($(this));
        });
        
        $.each(forms, function(i, form) {
                $(form).bind('reset', function(e) {
                        $(this).find('.opiElement').triggerHandler("focusout").parent().triggerHandler("focuseout");
                        //$(this).find('input[type="file"]').triggerHandler("focusout");
                        $(this).find(".ui-state-error").removeClass("ui-state-error");
                });
        })
    },

    processTemplate: function(field) {
        var that=this;
        var td=field.closest('td'), table=td.closest('table'), form=table.closest('form');
        var wrapper = $('#opiContainer');
        
        //MODIFY PRODUCT FORM
        var processMain = function() {
            td.closest('tr').addClass('trImageHead');
            table.css('width', '100%');//.closest('form').css({width:'99%', display:'block'});
            td.html('<button id="opiUploadBtn" type="button">'+that.options.buttons.xUpload+'</button> <button id="opiBrowseBtn" type="button">'+that.options.buttons.xBrowse+'</button> <button id="opiHelpBtn" type="button" title="">'+that.options.buttons.xHelp+'</button>');
            td.closest('tr').addClass('trImageLabel').after('<tr class="trImageList"><td class="main preview" valign="top"><div id="opiImageDefault"><img src="'+that.options.imageURL.transparent+'" /></div></td><td class="main listing" valign="top"><ul id="opiImageList" class="opiImageListing"></ul><div class="clear"></div><small class="fieldRequired">'+that.options.labels.tips+'</small></td></tr>');
            
            //IMAGE PRODUCTS DRAGABLE-SORTABLE
            $("#opiImageList").sortable({
                    update: function(event, ui){
                        if ($(ui.item).prev().length < 1) {
                            that.clickButtonPreview(ui.item);
                        } else {
                            that.clickButtonSorted(ui.item);
                        }
                        that.timerReset();
                    }
            }).disableSelection();
            
            //populate images
            if (jQuery.trim(that.options.products_images) != '') {
                var products_images = that.options.products_images.split(',');
                if (products_images.length > 0) {
                    $.each(products_images, function(i,img){
                        that.imageAddProcess(img, true);
                    });
                
                    that.clickButtonPreview($('#opiImageList').find('li:first'));
                }
            }
            imageListingDelegate();
        };
        
        var imageListingDelegate = function() {
            $('ul.opiImageListing').delegate('button', "click", function() {
                    var parentLi = $(this).closest('li');
                    
                    if ($(this).hasClass('btnRemove')) {
                        return that.clickButtonRemove(parentLi);
                    } else if ($(this).hasClass('btnPreview')) {
                        return that.clickButtonPreview(parentLi);
                    } else if ($(this).hasClass('btnDel')) {
                        return that.clickButtonDelete(parentLi);
                    } else if ($(this).hasClass('btnAdd')) {
                        return that.clickButtonAdd(parentLi);
                    }
            });
        };

        //INITIALIZE DIALOG
        var processDialog = function() {
            $('.opiDialog').hide();
            $('<iframe name="opiUploadFrame" id="opiUploadFrame" width="0" height="0" border="0" style="width:0; height:0; border:0;"></iframe>').appendTo(wrapper).load(function() {
                that.doUpload();
            });
        
            wrapper.append('<div id="opiAlertDialog" class="opiDialog" title="Alert Message"><div class="content divcentered"></div></div>');
            $('#opiAlertDialog').find('div.content').height(100);
            wrapper.find('.opiDialog').each(function(i){
                    var dialogOption = {autoOpen:false, autoFocus:false, focus:false, resizable:false, modal:true, height:390, width:440, minHeight:390, minWidth:440, open: function(e, ui) {that.timerReset();}, close: function(e, ui) {that.timerReset();}};            
                    var ids = this.id;
                    
                    $(this).prepend('<a class="opiDisableAutoFocus" href="'+document.location.href+'">&nbsp;</a>');
                    switch(ids) {
                    case 'opiAlertDialog':
                        $.extend(dialogOption, {
                                height:200, 
                                minWidth:300,
                                width:300, 
                                buttons: [{text:that.options.buttons.oke, title:'Oke', className:'primaries', click:function(){$(this).dialog("close")}}]
                        });
                        break;
                    case 'opiHelpDialog':
                        //$(this).find('dl').parent().prepend('<div style="position:absolute; right:0;"><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"><input type="hidden" name="cmd" value="_s-xclick"><input type="hidden" name="hosted_button_id" value="WFJJKSVSQ9FMQ"><input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="Donate"><img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"></form></div>');
                        //$(this).find('dl').parent().append('<div style="padding:10px; text-align:center; font-style: italic;">If you find this module useful, feel free to donate even for 1 dollar.<div><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"><input type="hidden" name="cmd" value="_s-xclick"><input type="hidden" name="hosted_button_id" value="WFJJKSVSQ9FMQ"><input type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="Donate"><img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1"></form></div></div>');
                        $.extend(dialogOption, {
                                resizable:true
                        });
                        break;
                    case 'opiUploadDialog':
                        var Button = [];
                        if (that.options.privileges.directory) {
                            Button.push({id: 'uploadBtnCreateDir', className:'secondaries btnIconized btnIconized-newwin', text:that.options.buttons.create, click: function() {$('#opiDirectoryDialog').dialog("open");}});
                        }
                        Button.push({id: 'uploadBtnSubmit', className:'primaries btnIconized btnIconized-disk', text:that.options.buttons.upload, click: function(e) {$(this).find('form').triggerHandler('submit');}});
                        //Button.push({id: 'uploadBtnClose', className:'secondaries opicon-close', text:that.options.buttons.close, click: function(e) {$(this).dialog("close");}});
                        
                        $.extend(dialogOption, {
                                width:580, minWidth:420,
                                open: function(e, ui) {
                                    that.timerReset();
                                    $(this).find('form').find('input[type="file"]').val('').triggerHandler('change');
                                    $(this).find('form').find('input[name="opi_rename"]').val($('#products_name_'+that.options.language_id).val());
                                    $('#uploadBtnSubmit').button("option", "disabled", false); 
                                    that.doTestGetDirectories($(this).find('select'), 0);
                                },
                                close: function(e, ui) {that.showHideMessage("hide", $('#opiUploadDialog')); that.timerReset(); $(this).find(".ui-state-error").removeClass("ui-state-error"); $(this).find('strong.dropdownContainer').hide();},
                                buttons:Button
                        });
                        $(this).find('form').attr("target","opiUploadFrame").submit(function(e) {
                                if (!that.doTestUpload(this)) {
                                    e.preventDefault();
                                    return false;
                                }
                                this.submit();
                                return true;
                        });
                        //$(this).find('form').attr("target","opiUploadFrame").submit(function(e) {
                                //if (!that.doTestUpload(this)) {
                                //    e.preventDefault();
                                //}
                        //});
                        break;
                    case 'opiDirectoryDialog':
                        $.extend(dialogOption, {
                                height:350, width:420, minHeight:350, minWidth:420,
                                open: function(e, ui) {
                                    that.timerReset();
                                    that.doTestGetDirectories($(this).find('select'), 0);
                                },
                                close: function(e, ui) {that.timerReset(); that.showHideMessage("hide", '#opiDirectoryDialog'); $(this).find(".ui-state-error").removeClass("ui-state-error"); $(this).find('strong.dropdownContainer').hide();},
                                buttons: [{id:"createBtnBack", text:that.options.buttons.back, title:'Back', className:'secondaries btnIconized btnIconized-triangle-1-w', click:function(){$(this).dialog("close");$('#opiUploadDialog').dialog("open")}},{id:'createBtnSubmit', text:that.options.buttons.submit, title:'Submit', className:'primaries btnIconized btnIconized-disk', click:function(){$(this).find('form').triggerHandler('submit');}}]
                        });
                        $(this).find('form').submit(function(e) {
                                e.preventDefault();
                                if (!that.doTestCreateDirectory(this)) {
                                    return false;
                                }
                                that.doCreateDirectory(this);
                                return true;
                        });
                        break;
                    case 'opiBrowseDialog':
                        $.extend(dialogOption, {
                                open: function(e, ui) {
                                    that.timerReset();
                                    $(this).find('div.content').height($('#opiBrowseDialog').height() - 2);
                                    var selectField = $(this).find('select');
                                    
                                    that.doTestGetDirectories($(this).find('select'), 0);
                                    that.listBrowseImagePrevNext(0);
                                },
                                close: function(e, ui) {that.timerReset();$(this).find('strong.dropdownContainer').hide();},
                                buttons: [
                                    {id:'btnBrowsePrev', text:'<', title: 'Previous',click: function(){that.listBrowseImagePrevNext(-1)}},
                                    {id: 'btnBrowseNext',text:'>', title: 'Next',click: function(){that.listBrowseImagePrevNext(1)}}
                                ]
                        });
                        $(this).find('form').submit(function(e) {
                                this.submit = false;
                                that.doBrowseFiles(this);
                                e.preventDefault();
                                return false;
                        });
                        $(this).find('form').find('select').bind('change', function(e) {
                                if (parseInt($(this).attr("selectedIndex")) > 0)  {
                                    $(this.form).find('label.inside[for="opi_folder_browse"]').hide();
                                    $(this.form).triggerHandler('submit');
                                } else {
                                    $(this.form).find('label.inside[for="opi_folder_browse"]').show();
                                }
                        });
                        break;
                    }
                    $('#'+ids).dialog(dialogOption);
            }); 
            wrapper.find('a.opiDisableAutoFocus').bind('click', function(e){e.preventDefault(); return false;}).bind('focus', function(){$(this).blur()});
            $('#btnBrowsePrev').button({label:'&laquo;', disabled:true}).next().button({label:'&raquo;', disabled:true}).closest('div.ui-dialog-buttonpane').prepend('<div class="ui-dialog-buttonleft"><div class="ui-dialog-label">'+that.options.labels.page+' <label class="page_index currentpage">0</label> '+that.options.labels.of+' <label class="page_index totalpage">0</label> - '+that.options.labels.from+' <label class="page_index totalitem">0</label> '+that.options.labels.files+' </div></div>');
            $('.opiDialog').closest('.ui-dialog').find('button.btnIconized').each(function(){
                    var cls = this.className.split('btnIconized-');
                    var icon = null;
                    try {
                        icon = cls[1].split(' ')[0];
                    } catch(e){}
                    if (icon) {
                        $(this).button({icons:{primary:"ui-icon-"+icon}});
                    }
            });
            $('.opiDialog').closest('.ui-dialog').find('button.secondaries').removeClass("ui-priority-primary").addClass("ui-priority-secondary");
            $('.opiDialog').closest('.ui-dialog').find('button.primaries').removeClass("ui-priority-secondary").addClass("ui-priority-primary");
            
            //bind button help
            $('#opiHelpBtn').button({icons:{secondary:"ui-icon-lightbulb"}}).addClass("ui-priority-secondary").bind('click', function() {
                    $('#opiHelpDialog').dialog("open");
                    return false;
            });
            //bind button upload
            $('#opiUploadBtn').button({icons:{secondary:"ui-icon-image"}}).addClass("ui-priority-secondary").bind('click', function() {
                    $('#opiUploadDialog').dialog("open");
                    return false;
            });
            //bind button browse
            $('#opiBrowseBtn').button({icons:{secondary:"ui-icon-folder-open"}}).addClass("ui-priority-secondary").bind('click', function() {
                    $('#opiBrowseDialog').dialog("open");
                    //$('#opiBrowseDialog').find('form').each(function(){this.reset()});
                    return false;
            });
        };
        

        
        //MODIFY LAYOUT - UI
        var processUI = function() {
            that.formDialogUI();
        };
        
        //hide dialog
        processMain();
        processDialog();
        processUI();
    },
        
    _setElementError: function(elem) {
        if ($(elem).attr('rel') && $($(elem).attr('rel')).length) {
            $($(elem).attr('rel')).addClass("ui-state-error").one('change', function() {
                    $(this).removeClass("ui-state-error");
            });
        } else {
            $(elem).addClass("ui-state-error").one('change', function() {
                    $(this).removeClass("ui-state-error");
            });
        }
    },
    
    preloadImage: function(imgUrl, callback) {
        var that = this;
        
        var oImg = $('<img />');
        oImg.bind('error', function() {
                $(this).unbind('load');
                $(this).unbind('error');
                $(this).hide();
                //FORCE get IMG
                that.preloadErrorImage(imgUrl, callback);
        }).bind('load', function() {
                $(this).unbind('error');
                $(this).unbind('load');
                callback(imgUrl);
                oImg.remove();
        }); 
        
        //oImg.attr('src', that.options.imageURL.small + imgFile); 
        //almost 99% jQuery attr.src resulting an error image corrupted 
        //for images not in browser cache. so we use native javascript src
        //Note: OsC use jQuery 1.4.2 that does not support .prop function
        oImg.get(0).src = imgUrl;
    },
    
    preloadErrorImage: function(imgUrl, callback) {
        var nt = 250;
        var imgCompleted = function() {
            nt = nt+250;
            if(img.complete) return true;
            return false;
        };
        var imgTimeout = function() {
            if (!imgCompleted() && nt < 50000) return setTimeout(imgTimeout, nt);
            return callback(imgUrl);
        };
        
        var img = new Image();
        //img.id = 'randomImagePreaload';
        img.src = imgUrl;
        if (callback) imgTimeout();
    },
    
    generateID: function(elem, index) {
        index++;
        var def = $(elem).attr('name') || elem.nodeName.toLowerCase();
        var retval = def+'_'+index;
        var found = $('#'+retval).length;
        while(($('#'+retval).length) > 0) {
            index++;
            retval = def+'_'+index;
        }
        elem.id = retval;
        
        return retval;
    },
    
    data: null
};

oscProductImage.initialize('products_image', oscProductImageHelper);

